package net.mikoo.seals.boss.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import net.mikoo.seals.boss.biz.services.PartyServices;
import net.mikoo.seals.boss.biz.services.RolePermitService;
import net.mikoo.seals.boss.biz.services.RoleServices;
import net.mikoo.seals.boss.biz.services.UserLoginServices;
import net.mikoo.seals.boss.common.BaseController;
import net.mikoo.seals.boss.common.WebContext;
import net.mikoo.seals.boss.common.enums.PartyTypeEnum;
import net.mikoo.seals.boss.common.exception.AccountDisabledException;
import net.mikoo.seals.boss.common.exception.AccountExpiryException;
import net.mikoo.seals.boss.common.exception.AccountFreezedException;
import net.mikoo.seals.boss.common.exception.AccountNotFindException;
import net.mikoo.seals.boss.common.exception.ParametersException;
import net.mikoo.seals.boss.common.exception.PasswordErrorException;
import net.mikoo.seals.boss.common.utils.MD5Util;
import net.mikoo.seals.boss.model.Menu;
import net.mikoo.seals.boss.model.Party;
import net.mikoo.seals.boss.model.Role;
import net.mikoo.seals.boss.model.UserLogin;


@Controller
@RequestMapping("/admin")
public class AdminController extends BaseController{
	

	Logger logger = Logger.getLogger(AdminController.class);

	@Autowired
	private UserLoginServices userLoginServices;
	
	
	@Autowired
	private PartyServices partyServices;
	
	@Autowired
	private RolePermitService rolePermitService;
	
	@Autowired
	private RoleServices roleServices;
	
	@Autowired
	private AuthenticationManager myAuthenticationManager;


	/**
	 * 登录界面
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/login")
	public String login(HttpServletRequest request, Model model) {
		
	/*	try{
			getLoginUser(request);
			//model.addAttribute("userLogin", userLogin);
		}catch(UserNotLoginException e){
			return this.resultView(ADMIN_VIEW,"login");
		}*/
		//String basePath = (String) request.getAttribute("basePath");
		//return redirect(basePath+"member/main.htm",model);
		
		return this.resultView(ADMIN_VIEW,"login");
	}

	/**
	 * 登录
	 * 
	 * @param username
	 * @param password
	 * @param code
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/signin", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> signin(Model model, HttpServletRequest request)  {
		
		Map<String, Object> webResult = new HashMap<>();
		
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String authcode = request.getParameter("authcode");

		try {

			HttpSession session = request.getSession();
			String kaptchaCode = (String) session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
			if (StringUtils.isEmpty(authcode) || StringUtils.isEmpty(kaptchaCode) || !kaptchaCode.equals(authcode)) {
				logger.error("验证码出错！");
				return result(ERROR,"验证码错误");
			}

			Party party = userLoginServices.authLogin(username, password, PartyTypeEnum.OPERATOR.code());

			Authentication authentication = myAuthenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, MD5Util.Md5(password)));
			SecurityContext securityContext = SecurityContextHolder.getContext();
			securityContext.setAuthentication(authentication);
			session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);

			retainSession(party, request, WebContext.ADMIN_LOGIN_SESSION_KEY);
			return result(SUCCESS,"登陆成功");
			// return redirectTips("/admin/login.htm", "用户名或密码错误", model);

		} catch (ParametersException | AccountNotFindException | AccountDisabledException| AccountFreezedException |AccountExpiryException| PasswordErrorException e) {
			logger.error("", e);
			return result(ERROR,e.getMessage());
		} catch (Exception e) {
			logger.error("登录系统出错！", e);
			return result(ERROR,"系统出错，请联系管理员");
		}
	}

	/**
	 * 登出
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request, Model model) {
		
		removeSession(request,WebContext.ADMIN_LOGIN_SESSION_KEY);
		removeSession(request,"_menus");
		//String basePath = (String) request.getAttribute("basePath");
		return this.redirect("/admin/login.htm", model);
	}
	
	
	@RequestMapping("/dashboard/index")
	public String index(HttpServletRequest request,Model model) {
		UserLogin userLogin = getLoginUser(request,WebContext.ADMIN_LOGIN_SESSION_KEY);
		Party party = getParty(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
		
		Role role = new Role();
		role.setPartyId(party.getPartyId());
		List<Role> roles = roleServices.selectByQuery(role);
		
		model.addAttribute("roles", roles);
		model.addAttribute("userLogin", userLogin);
		return resultView(ADMIN_VIEW,"index");
	}
	
	
	/**
	 * 管理界面菜单
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/menu")
	public String menu(Long menuId,HttpServletRequest request,Model model) {
		UserLogin userLogin = getLoginUser(request,WebContext.ADMIN_LOGIN_SESSION_KEY);
		if(userLogin == null){
			return redirect("/admin/login.htm");
		}
		List<Menu> menus = rolePermitService.loadSubResource(userLogin.getPartyId(), menuId);
		model.addAttribute("menus", menus);
		return resultView(ADMIN_VIEW,"menu");
	}
	
	/**
	 * 管理主界面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/main")
	public String main(HttpServletRequest request,Model model) {
		
		UserLogin userLogin = getLoginUser(request,WebContext.ADMIN_LOGIN_SESSION_KEY);
		if(userLogin == null){
			return redirect("/admin/login.htm");
		}
		List<Menu> menus = rolePermitService.loadRootResource(userLogin.getPartyId());
		model.addAttribute("userLogin", userLogin);
		model.addAttribute("menus", menus);
		return resultView(ADMIN_VIEW,"main");
	}
	
	
	
	/**
	 * ajax验证登录帐户是否唯一
	 * 
	 * @param userLoginId
	 * @return
	 */
	@RequestMapping("/usernameIsUnique")
	@ResponseBody
	public Map<String, String> usernameIsUnique(String userLoginId, String excludeKey) {
		Map<String, String> res = new HashMap<String, String>();

		Boolean b = partyServices.checkExist(userLoginId, excludeKey, "username");
		if (b) {
			res.put("code", "1");
			return res;
		} else {
			res.put("code", "0");
			return res;
		}
		// res.put("code", "-1");
		// res.put("message", result.getMessage());
		//
		// return res;
	}

	/**
	 * ajax验证邮箱帐户是否唯一
	 * 
	 * @param userLoginId
	 * @return
	 */
	@RequestMapping("/emailIsUnique")
	@ResponseBody
	public Map<String, String> emailIsUnique(String email, String excludeKey) {

		Map<String, String> res = new HashMap<String, String>();

		Boolean b = partyServices.checkExist(email, excludeKey, "email");
		if (b) {
			res.put("code", "1");
			return res;
		} else {
			res.put("code", "0");
			return res;
		}
		//res.put("code", "-1");
		//res.put("message", result.getMessage());

		//return res;

	}

	
	
//	public static void main(String[] args) {
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
//		sdf.parse("d");
//	}
	
}
